package com.ttc.ssm.controller.admin;

import com.ttc.ssm.common.CustomerPage;
import com.ttc.ssm.po.*;
import com.ttc.ssm.service.admin.CommonService;
import com.ttc.ssm.service.admin.CustomerService;
import com.ttc.ssm.utils.DateUtils;
import com.ttc.ssm.utils.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;

/**
 * Created by 58296 on 2016/7/25.
 */
@Controller
@RequestMapping("admin/customer")
public class CustomerController {

    @Autowired
    CustomerService customerService;

    @Autowired
    CommonService commonService;

    @RequestMapping("index")
    public String index(Model model) throws Exception {
        return "admin/customer/index";
    }

    @RequestMapping("/getCustomerList")
    public @ResponseBody Map getCustomerList(@RequestParam("p") Integer page,@RequestParam("fullname") String fullname) throws Exception {
        System.out.println(page);
        CustomerPage customerPage = new CustomerPage();
        customerPage.setPageSize(20);
        customerPage.setCurrentPage(page);
        Map where = new HashMap();
        if(!(fullname==null)){
            customerPage.setFullname(fullname);
            where.put("fullname",fullname);
        }
        customerPage.setTotalRows(customerService.totalRows(where));
        List<Customer> customers = customerService.getCustomerForPage(customerPage);
        Map map = new HashMap();
        map.put("data",customers);
        map.put("show",customerPage);
        System.out.println(customers);
        return map;
    }

    @RequestMapping("detail")
    public ModelAndView detail(@RequestParam("customer_id") Integer customer_id) throws Exception {
        Customer customer = customerService.getCustomerById(customer_id);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("customer", customer);
        modelAndView.setViewName("admin/customer/detail");
        return modelAndView;
    }

    @RequestMapping("deleteCustomers")
    @ResponseBody
    public int deleteCustomers(@RequestBody Map ids) throws  Exception{
        try {
            customerService.deleteCustomer(ids);
            return 1;
        }catch (Exception e){
            return 0;
        }
    }

    @RequestMapping("/updateCustomerStatus")
    @ResponseBody
    public int updateCustomerStatus(@RequestParam("customer_id") int customer_id,@RequestParam("status") int status) throws Exception{
        try {
            customerService.updateCustomerStatus(customer_id,status);
            return 1;
        }catch (Exception e){
            return 0;
        }
    }

    @RequestMapping("edit")
    public String edit(Model model, @RequestParam("customer_id") int customer_id) throws Exception{
        Customer customer = customerService.getCustomerById(customer_id);
        model.addAttribute("customer", customer);
        return "admin/customer/edit";
    }

    @RequestMapping("/saveCustomer")
    @ResponseBody
    public Object saveCustomer(HttpServletRequest request, Customer customer, @RequestParam(value = "input01") MultipartFile temp_pic) throws Exception
    {
        try{
            if(customer.getFullname()==null || customer.getSex()==null
                    || customer.getEmail()==null || customer.getTelephone()==null)
                return -1;

            String originalFilename = temp_pic.getOriginalFilename();
            System.out.println(originalFilename);
            if(temp_pic !=null && originalFilename !=null && originalFilename.length()>0) {
                //存储图片的物理路径
                String pic_path=request.getSession().getServletContext().getRealPath("upload/customer/");
                //新的图片名称
                String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
                System.out.println(pic_path + newFileName);
                //新图片
                File newFile = new File(pic_path + newFileName);

                //将内存的数据写入磁盘
                temp_pic.transferTo(newFile);
                customer.setHeadimgurl(newFileName);
            }
            Date d = new Date();
            customer.setDate_modified(d);
            customerService.updateCustomerById(customer);
            return 1;
        }catch (Exception e){
            return 0;
        }
    }

    @RequestMapping("resumeIndex")
    public String resumeIndex(Model model) throws Exception
    {
        return "admin/customer/resumeIndex";
    }

    @RequestMapping("/getResumeList")
    public @ResponseBody Map getResumeList(@RequestParam("p") Integer page,@RequestParam("fullname") String fullname) throws Exception
    {
        System.out.println(page);
        CustomerPage customerPage = new CustomerPage();
        customerPage.setPageSize(20);
        customerPage.setCurrentPage(page);
        Map where = new HashMap();
        if(!(fullname==null)){
            customerPage.setFullname(fullname);
            where.put("fullname",fullname);
        }
        customerPage.setTotalRows(customerService.totalResumeRows(where));
        List<Resume> resumes = customerService.selectResumeForPage(customerPage);
        Map map = new HashMap();
        map.put("data",resumes);
        map.put("show",customerPage);
        map.put("da",customerService.selectResumeById(2));
        System.out.println(resumes);
        return map;
    }

    @RequestMapping("deleteResumes")
    @ResponseBody
    public int deleteResumes(@RequestBody Map ids) throws  Exception
    {
        try {
            customerService.deleteResumes(ids);
            return 1;
        }catch (Exception e){
            return 0;
        }
    }

    @RequestMapping("editResume")
    public String editResume(Model model, @RequestParam("resume_id") Integer resume_id) throws Exception
    {
        Resume resume = customerService.selectResumeById(resume_id);
        List<Zone> zoneList = commonService.getZone();
        List<City> origin_cityList = commonService.getCityByZoneId(resume.getOrigin_city().getZone_id());
        List<City> live_cityList = commonService.getCityByZoneId(resume.getLive_city().getZone_id());
        List<City> expect_cityList = commonService.getCityByZoneId(resume.getExpect_city().getZone_id());
        List<Industry> industryList = commonService.getIndustry();
        List<SalaryType> salaryTypeList = commonService.getSalaryType();
        List<JobType> jobTypeList = commonService.getJobType();
        List<WorkExp> workExpList  = customerService.selectWorkByResumeId(resume_id);
        List<Education> educationList  = customerService.selectEduByResumeId(resume_id);
        List<CompetitionExp> competitionExpList  = customerService.selectComByResumeId(resume_id);
        List<Skill> skillList = customerService.selectSkillByResumeId(resume_id);

        model.addAttribute("resume", resume);
        model.addAttribute("zoneList",zoneList);
        model.addAttribute("origin_cityList",origin_cityList);
        model.addAttribute("live_cityList",live_cityList);
        model.addAttribute("expect_cityList",expect_cityList);
        model.addAttribute("industryList",industryList);
        model.addAttribute("salaryTypeList",salaryTypeList);
        model.addAttribute("jobTypeList",jobTypeList);

        model.addAttribute("workExpList",workExpList);
        model.addAttribute("educationList",educationList);
        model.addAttribute("competitionExpList",competitionExpList);
        model.addAttribute("skillList",skillList);
        return "admin/customer/resumeEdit";
    }

    @RequestMapping("/getCityList")
    @ResponseBody
    public List<City> getCityList(@RequestParam("zone_id") Integer zone_id) throws Exception
    {
        return commonService.getCityByZoneId(zone_id);
    }

    @RequestMapping("/saveResume")
    @ResponseBody
    public Object saveResume(HttpServletRequest request, Resume resume, @RequestParam("input20") MultipartFile temp_file) throws Exception
    {
        try {
            if (resume.getResume_id() == null || resume.getRealname() == null) {
                return -1;
            }
            if (resume.getBirthday_string()!=null) {
                Date date = DateUtils.stringToDate(resume.getBirthday_string());
                resume.setBirthday(date);
            }
            String originalFilename = temp_file.getOriginalFilename();
            if(temp_file !=null && originalFilename !=null && originalFilename.length()>0) {
                //存储图片的物理路径
                String file_path=request.getSession().getServletContext().getRealPath("upload/customer/");
                //新的图片名称
                String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
                System.out.println(file_path + newFileName);
                //新图片
                File newFile = new File(file_path + newFileName);

                //将内存的数据写入磁盘
                temp_file.transferTo(newFile);
                resume.setAttachment(newFileName);
                Resume tmp_resume = customerService.selectResumeById(resume.getResume_id());
                if (tmp_resume.getAttachment() != null) {
                    deleteFile(tmp_resume,request);
                }
            }
            System.out.println(resume.getComment());
            customerService.updateResumes(resume);
            return 1;
        }catch (Exception e) {

            return 0;
        }

    }

    public static void deleteFile(Resume resume, HttpServletRequest request) {

        if (!(resume.getAttachment() ==null)){
            String pic_path=request.getSession().getServletContext().getRealPath("upload/customer/");
            String old_file_name = pic_path+resume.getAttachment();
            File old_File = new File(old_file_name);
            if(old_File.exists()){
                old_File.delete();
            }
        }
    }

    @RequestMapping("/saveSkill")
    @ResponseBody
    public int saveSkill(@RequestBody Skill skill) throws Exception
    {
        if (skill == null || skill.getArr() == null || skill.getResume_id()==null) {
            return -1;
        }
        try {
            System.out.println(skill.getArr());
            Iterator iterator2 = skill.getArr().iterator();
            Skill temp;
            Map map = new HashMap();
            List<Integer> ids = getIds(iterator2);
            map.put("ids",ids);
            map.put("resume_id",skill.getResume_id());
            customerService.deleteSkillById(map);
            Iterator iterator = skill.getArr().iterator();
            while (iterator.hasNext()) {
                List list;
                if ((list = (List) iterator.next())!=null) {
                    temp = new Skill();
                    temp.setResume_id(skill.getResume_id());
                    if (list.get(1) != null) {
                        temp.setName((String) list.get(1));
                        System.out.println(temp.getName());
                        if (list.get(0) == null || list.get(0).equals("")) {
                            customerService.insertSkill(temp);
                        }else {
                            Integer skill_id = Integer.valueOf((String)list.get(0));
                            System.out.println(skill_id);
                            temp.setSkill_id(skill_id);
                            customerService.updateSkill(temp);
                        }
                    }

                }
            }

            return 1;
        }catch (Exception e) {

            return 0;
        }
    }

    @RequestMapping("/saveWorkExp")
    @ResponseBody
    public int saveWorkExp(@RequestBody WorkExp workExp) throws Exception
    {
        System.out.println(workExp.getArr());
        if (workExp == null || workExp.getArr() == null || workExp.getResume_id()==null) {
            return -1;
        }
        try {
            System.out.println(workExp.getArr());
            WorkExp temp;
            Iterator iterator2 = workExp.getArr().iterator();
            Map map = new HashMap();
            List<Integer> ids = getIds(iterator2);
            map.put("ids",ids);
            map.put("resume_id",workExp.getResume_id());
            customerService.deleteWorkById(map);
            Iterator iterator = workExp.getArr().iterator();
            while (iterator.hasNext()) {
                List list;
                if ((list = (List) iterator.next())!=null) {
                    temp = new WorkExp();
                    temp.setResume_id(workExp.getResume_id());
                    String text = (String) list.get(1);
                    String date_start = (String) list.get(2);
                    String date_end = (String) list.get(3);
                    if (!TextUtils.isEmpty(text) && !TextUtils.isEmpty(date_end) && !TextUtils.isEmpty(date_start)) {
                        temp.setText(text);
                        temp.setDate_start(DateUtils.stringToDate(date_start));
                        temp.setDate_end(DateUtils.stringToDate(date_end));
                        if (TextUtils.isEmpty((String) list.get(0))) {
                            customerService.insertWork(temp);
                        }else {
                            Integer work_exp_id = Integer.valueOf((String)list.get(0));
                            System.out.println(work_exp_id);
                            temp.setWork_exp_id(work_exp_id);
                            customerService.updateWork(temp);
                        }
                    }

                }
            }
            return 1;
        }catch (Exception e) {

            return 0;
        }
    }

    @RequestMapping("/saveComExp")
    @ResponseBody
    public int saveComExp(@RequestBody CompetitionExp competitionExp) throws Exception
    {
        if (competitionExp == null || competitionExp.getArr() == null || competitionExp.getResume_id()==null) {
            return -1;
        }
        try {
            System.out.println(competitionExp.getArr());
            Iterator iterator2 = competitionExp.getArr().iterator();

            Map map = new HashMap();
            List<Integer> ids = getIds(iterator2);
            map.put("ids",ids);
            map.put("resume_id", competitionExp.getResume_id());
            customerService.deleteComById(map);
            Iterator iterator = competitionExp.getArr().iterator();
            CompetitionExp temp;
            while (iterator.hasNext()) {
                List list;
                if ((list = (List) iterator.next())!=null) {
                    temp = new CompetitionExp();
                    temp.setResume_id(competitionExp.getResume_id());
                    String name = (String) list.get(1);
                    String obtain = (String) list.get(2);
                    String date = (String) list.get(3);
                    if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(obtain) && !TextUtils.isEmpty(date)) {
                        temp.setName(name);
                        temp.setObtain(obtain);
                        temp.setDate(DateUtils.stringToDate(date));
                        System.out.println(name);
                        if (TextUtils.isEmpty((String) list.get(0))) {
                            customerService.insertCom(temp);
                        }else {
                            Integer competition_exp_id = Integer.valueOf((String)list.get(0));
                            System.out.println(competition_exp_id);
                            temp.setCompetition_exp_id(competition_exp_id);
                            customerService.updateCom(temp);
                        }
                    }
                }
            }

            return 1;
        }catch (Exception e) {

            return 0;
        }
    }

    @RequestMapping("/saveEdu")
    @ResponseBody
    public int saveEdu(@RequestBody Education education) throws Exception
    {
        if (education == null || education.getArr() == null || education.getResume_id()==null) {
            return -1;
        }
        try {
            System.out.println(education.getArr());
            Iterator iterator2 = education.getArr().iterator();
            Map map = new HashMap();
            List<Integer> ids = getIds(iterator2);
            map.put("ids",ids);
            map.put("resume_id", education.getResume_id());
            customerService.deleteEduById(map);
            Iterator iterator = education.getArr().iterator();
            Education temp;
            while (iterator.hasNext()) {
                List list;
                if ((list = (List) iterator.next())!=null) {
                    temp = new Education();
                    temp.setResume_id(education.getResume_id());
                    String school = (String) list.get(1);
                    String date_start = (String) list.get(2);
                    String date_end = (String) list.get(3);
                    if (!TextUtils.isEmpty(school) && !TextUtils.isEmpty(date_start) && !TextUtils.isEmpty(date_end)) {
                        temp.setSchool(school);
                        temp.setDate_start(DateUtils.stringToDate(date_start));
                        temp.setDate_end(DateUtils.stringToDate(date_end));
                        System.out.println(school);
                        if (TextUtils.isEmpty((String) list.get(0))) {
                            customerService.insertEdu(temp);
                        }else {
                            Integer education_id = Integer.valueOf((String)list.get(0));
                            System.out.println(education_id);
                            temp.setEducation_id(education_id);
                            customerService.updateEdu(temp);
                        }
                    }
                }
            }
            return 1;
        }catch (Exception e) {

            return 0;
        }
    }

    private  List<Integer> getIds(Iterator iterator)
    {
        List<Integer> ids = new ArrayList();
        while (iterator.hasNext()) {
            List list;
            if ((list = (List) iterator.next())!=null) {
                if (!TextUtils.isEmpty((String) list.get(0))) {
                    Integer id = Integer.valueOf((String)list.get(0));
                    ids.add(id);
                }
            }
        }
        return ids;
    }
}
